package com.hmy.cornpestdet.service;

import com.hmy.cornpestdet.mapper.AdminUserInfoMapper;
import com.hmy.cornpestdet.pojo.User;
import com.hmy.cornpestdet.utils.CPDConst;
import com.hmy.cornpestdet.utils.Result;
import com.hmy.cornpestdet.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@Service
public class AdminUserInfoService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private AdminUserInfoMapper adminUserInfoMapper;
    @Autowired UserLoginRegisterService userLoginRegisterService;

    public List<User> getAllUser(){
        return adminUserInfoMapper.getAllUser();
    }

    public int deleteUserByUid(int uid){
        return adminUserInfoMapper.deleteUserByUid(uid);
    }

    public Result getUserByUid(int uid){
        User user = adminUserInfoMapper.getUserByUid(uid);
        if(user == null)return Result.Error("编辑用户信息失败");
        return Result.Success("编辑用户信息成功",user);
    }

    public Result addUser(UserRegisterVo userRegisterVo) {
        User user = userLoginRegisterService.getUserByPhoneNumber(userRegisterVo.getPhoneNumber());
        if(user != null){
            return Result.Error("该手机号码已被注册");
        }
        user = userLoginRegisterService.getUserByUsername(userRegisterVo.getUsername());
        if(user != null){
            return Result.Error("该用户名已被注册");
        }

        User insertUser = new User();
        insertUser.setUsername(userRegisterVo.getUsername());
        insertUser.setPassword(userRegisterVo.getPassword());
        insertUser.setCharacter(CPDConst.CHARACTER_NORMAL);
        insertUser.setPhoneNumber(userRegisterVo.getPhoneNumber());
        insertUser.setRegisterDate(userRegisterVo.getRegisterDate());
        adminUserInfoMapper.addUser(insertUser);
        if(insertUser.getUid() > 0)return Result.Success("新增用户成功",getAllUser());
        return Result.Error("新增用户失败");
    }

    public Result updateUserByUid(int uid, String username,String password,String phoneNumber){
        User user = userLoginRegisterService.getUserByPhoneNumber(phoneNumber);
        if(user != null && user.getUid() != uid){
            return Result.Error("该手机号码已被注册");
        }
        user = userLoginRegisterService.getUserByUsername(username);
        if(user != null){
            return Result.Error("该用户名已被注册");
        }

        if(adminUserInfoMapper.updateUserByUid(uid,username,password,phoneNumber) < 1){
            return Result.Error("修改失败,请检查网络");
        }
        return Result.Success("修改成功",getAllUser());

    }

}
